/**
 * Copyright (c) 2009 RiseSoft Co.,Ltd  
 * $Header$
 */
package net.risesoft.risebi.collection.web.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.risesoft.risebi.collection.commons.miscellaneouse.SystemStarter;
import net.risesoft.risebi.collection.event.EventObject;
import net.risesoft.risebi.collection.event.eventobj.SystemLogEventObj;
import net.risesoft.risebi.collection.model.EventListener;
import net.risesoft.risebi.collection.model.Service;
import net.risesoft.risebi.collection.model.SystemLog;
import net.risesoft.risebi.collection.model.User;
import net.risesoft.risebi.collection.service.EventListenerManager;
import net.risesoft.risebi.collection.web.BaseAction;
import net.risesoft.risebi.commons.util.ContextUtil;
import net.risesoft.risebi.commons.util.GUID;
import net.risesoft.risebi.commons.util.JSONUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

/**
 *
 * @author <a href="mailto: dingzhaojun@risesoft.net">丁兆俊</a>
 * @version $Revision$
 * 
 */
@Namespace("/admin/EventListenerAction")
public class EventListenerAction extends BaseAction{
	private static final long serialVersionUID = -5000258621248696911L;
	private static Log log = LogFactory.getLog(EventListenerAction.class);
	
	private EventListenerManager eventListenerManager;	
	private EventListener eventListener;
	
	private String field; //Ext.ux.plugins.RemoteValidator
	private String value; //Ext.ux.plugins.RemoteValidator
	private String crud;

	@Action(value="prepareListenerList",
			results={@Result(name="success", location="/admin/eventlistener/listenerList.jsp")}
	)
	public String prepareListenerList() throws Exception {
		return SUCCESS;
	}
	
	@Action(value="prepareListenerList2",
			results={@Result(name="success", location="/admin/eventlistener/listenerList2.jsp")}
	)
	public String prepareListenerList2() throws Exception {
		return SUCCESS;
	}
	
	@Action(value="prepareCodeView",
			results={@Result(name="success", location="/admin/eventlistener/codeView.jsp")}
	)
	public String prepareCodeView() throws Exception {
		eventListener = (EventListener)eventListenerManager.getObject(EventListener.class, node);
		json = eventListener.getContent();
		
		return SUCCESS;
	}

	@Action(value="prepareCodeEdit",
			results={@Result(name="success", location="/admin/eventlistener/codeEdit.jsp")}
	)
	public String prepareCodeEdit() throws Exception {
		eventListener = (EventListener)eventListenerManager.getObject(EventListener.class, node);
		json = eventListener.getContent();
		
		return SUCCESS;
	}

	public String getEventNames() throws Exception {
		JSONArray jsonArray = new JSONArray();
		
		SystemStarter ss = (SystemStarter) ContextUtil.getAc().getBean("systemStarter");
		List<Class> eventClasses = ss.getEventClasses();
		
		for(Class clazz:eventClasses){
			JSONObject jsonObj = new JSONObject();
			EventObject eo = (EventObject) clazz.getAnnotation(EventObject.class);
			jsonObj.element("guid", eo.eventName());
			
			String name = eo.eventName() + "(" + clazz.getSimpleName() + ")";
			jsonObj.element("name", name);
			jsonArray.add(jsonObj);
		}
		
		this.json = jsonArray.toString();
		return this.json;
	}
	
	@Action(value="prepareEdit",
			results={@Result(name="success", location="/admin/eventlistener/listenerEdit.jsp")}
	)
	public String prepareEdit() throws Exception {
		if(eventListener==null){
			eventListener = new EventListener();
			eventListener.setGuid(new GUID().toString(32));
		}else{
			eventListener = (EventListener)eventListenerManager.getObject(EventListener.class, eventListener.getGuid());
		}
		if(eventListener.getEnabled()==null) eventListener.setEnabled(true);
		if(eventListener.getLanguage()==null) eventListener.setLanguage(2);
		if(eventListener.getTabIndex()==null) eventListener.setTabIndex(1d);		
		
		getEventNames();
				
		return SUCCESS;
	}
	
	@Action(value="refreshJson")
	public String refreshJson() throws Exception {
		try{
			if("jsonListeners".equalsIgnoreCase(this.whichJson)){
				if(eventListener==null) eventListener = new EventListener();				
				Map map = (Map)eventListenerManager.getPagedListenerByListener(eventListener, start, limit);			
				this.json = JSONUtil.getJsonString("exclude","content",map);				
			}else if("jsonEventNames".equalsIgnoreCase(this.whichJson)){
				getEventNames();				
			}else if("jsonEventListeners".equalsIgnoreCase(this.whichJson)){
				Map map = (Map)eventListenerManager.getPagedListenerByEventName(this.node, start, limit);			
				this.json = JSONUtil.getJsonString("exclude","content",map);				
			}
		}catch(Exception e){
			this.json = "[]";
			e.printStackTrace();
		} 

		return AJAX;
	}

	@Action(value="edit")
	public String edit() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			User user = this.getSessionUser();
			
			if("c".equals(crud)){
				eventListenerManager.saveObject(eventListener);
				
//        		记录日志
				SystemLog systemLog = new SystemLog();
        		systemLog.setOpterateType(SystemLog.OPTERATETYPE_ADD);
        		systemLog.setUser(user);
        		
        		Service service = this.getDefaultService();
        		systemLog.setServiceGuid(service.getGuid());
        		
        		net.risesoft.risebi.collection.event.eventobj.EventObject systemLogEventObject = new SystemLogEventObj(this);
        		Map systemLogMap = new HashMap();
        		systemLogMap.put("systemLog", systemLog);
        		systemLogMap.put("keyName", "eventListeneradd");
        		systemLogMap.put("e", eventListener);
        		
        		systemLogEventObject.setDataMap(systemLogMap);
        		ContextUtil.getAc().publishEvent(systemLogEventObject);
			}else if("u".equals(crud)){
				EventListener old = (EventListener)eventListenerManager.getObject(EventListener.class, eventListener.getGuid());
				//old.setContent(content)
				old.setDescription(eventListener.getDescription());
				old.setEventNames(eventListener.getEventNames());
				old.setName(eventListener.getName());
				old.setEnabled(eventListener.getEnabled());
				old.setLanguage(eventListener.getLanguage());
				old.setTabIndex(eventListener.getTabIndex());
				
				eventListenerManager.saveObject(old);
				
//        		记录日志
				SystemLog systemLog = new SystemLog();
        		systemLog.setOpterateType(SystemLog.OPTERATETYPE_EDIT);
        		systemLog.setUser(user);
        		
        		Service service = this.getDefaultService();
        		systemLog.setServiceGuid(service.getGuid());
        		
        		net.risesoft.risebi.collection.event.eventobj.EventObject systemLogEventObject = new SystemLogEventObj(this);
        		Map systemLogMap = new HashMap();
        		systemLogMap.put("systemLog", systemLog);
        		systemLogMap.put("keyName", "eventListeneredit");
        		systemLogMap.put("e", old);
        		
        		systemLogEventObject.setDataMap(systemLogMap);
        		ContextUtil.getAc().publishEvent(systemLogEventObject);
			}
			
			ldb.set("guid", eventListener.getGuid());
			ldb.set("name", eventListener.getName());
			ldb.set("description", eventListener.getDescription());
			ldb.set("eventNames", eventListener.getEventNames());
			ldb.set("enabled", eventListener.getEnabled());
			ldb.set("language", eventListener.getLanguage());
			ldb.set("tabIndex", eventListener.getTabIndex());
			
			ldb.set("success", true);
			ldb.set("reason", "保存成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}

	@Action(value="editCode")
	public String editCode() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			EventListener old = (EventListener)eventListenerManager.getObject(EventListener.class, eventListener.getGuid());
			old.setContent(eventListener.getContent());
			eventListenerManager.saveObject(old);
			
			User user = this.getSessionUser();
			
//    		记录日志
			SystemLog systemLog = new SystemLog();
    		systemLog.setOpterateType(SystemLog.OPTERATETYPE_EDIT);
    		systemLog.setUser(user);
    		
    		Service service = this.getDefaultService();
    		systemLog.setServiceGuid(service.getGuid());
    		
    		net.risesoft.risebi.collection.event.eventobj.EventObject systemLogEventObject = new SystemLogEventObj(this);
    		Map systemLogMap = new HashMap();
    		systemLogMap.put("systemLog", systemLog);
    		systemLogMap.put("keyName", "eventListenerCodeedit");
    		systemLogMap.put("e", old);
    		
    		systemLogEventObject.setDataMap(systemLogMap);
    		ContextUtil.getAc().publishEvent(systemLogEventObject);
			
			ldb.set("success", true);
			ldb.set("reason", "保存程序代码成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}

	@Action(value="remove")
	public String remove() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			EventListener obj = (EventListener) eventListenerManager.getObject(EventListener.class, node);
			
			eventListenerManager.removeObject(EventListener.class, node);
			
			User user = this.getSessionUser();
			
//    		记录日志
			SystemLog systemLog = new SystemLog();
    		systemLog.setOpterateType(SystemLog.OPTERATETYPE_EDIT);
    		systemLog.setUser(user);
    		
    		Service service = this.getDefaultService();
    		systemLog.setServiceGuid(service.getGuid());
    		
    		net.risesoft.risebi.collection.event.eventobj.EventObject systemLogEventObject = new SystemLogEventObj(this);
    		Map systemLogMap = new HashMap();
    		systemLogMap.put("systemLog", systemLog);
    		systemLogMap.put("keyName", "eventListenerremove");
    		systemLogMap.put("e", obj);
    		
    		systemLogEventObject.setDataMap(systemLogMap);
    		ContextUtil.getAc().publishEvent(systemLogEventObject);
			
			ldb.set("success", true);
			ldb.set("reason", "删除成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		
		return AJAX;		
	}

	@Action(value="validateName")
	public String validateName() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();		
		if("c".equals(this.crud)){
			Integer count = eventListenerManager.getCount("select count(*) from EventListener t where t.name='" + this.value.trim() + "'");
			if(count>0){
				ldb.set("success", true);
				ldb.set("valid", false);
				ldb.set("reason", "名称重复。");
			}else{
				ldb.set("success", true);
				ldb.set("valid", true);
				ldb.set("reason", "名称不重复，可以使用。");
			}
		}else if("u".equals(this.crud)){
			Integer count = eventListenerManager.getCount("select count(*) from EventListener t where t.name='" + this.value.trim() + "' and t.guid !='" + this.node + "'");
			if(count>0){
				ldb.set("success", true);
				ldb.set("valid", false);
				ldb.set("reason", "名称重复。");
			}else{
				ldb.set("success", true);
				ldb.set("valid", true);
				ldb.set("reason", "名称不重复，可以使用。");
			}
		}
		
		this.json = JSONObject.fromObject(ldb).toString();	
		return AJAX;
	}
	
	public EventListenerManager getEventListenerManager() {
		return eventListenerManager;
	}

	public void setEventListenerManager(EventListenerManager eventListenerManager) {
		this.eventListenerManager = eventListenerManager;
	}

	public EventListener getEventListener() {
		return eventListener;
	}

	public void setEventListener(EventListener eventListener) {
		this.eventListener = eventListener;
	}

	public String getField() {
		return field;
	}

	public void setField(String field) {
		this.field = field;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getCrud() {
		return crud;
	}

	public void setCrud(String crud) {
		this.crud = crud;
	}
}
